﻿using Microsoft.AspNetCore.Http;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace XYS.Service.Core.Filters
{
    /// <summary>
    /// swagger 文件上传过滤器
    /// </summary>
    public class SwaggerFileUploadFilter : IOperationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            const string fileUploadContentType = "multipart/form-data";
            if (operation.RequestBody == null)
                return;

            if (context.ApiDescription.ParameterDescriptions.Any(p => p.Type == typeof(IFormCollection)))
            {
                var oldbodyContents = operation.RequestBody.Content.Where(e => e.Key != fileUploadContentType).ToList();

                operation.RequestBody = new OpenApiRequestBody();
                var openApiMediaType = new OpenApiMediaType()
                {
                    Schema = new OpenApiSchema()
                    {
                        Description = "文件",
                        Type = "object",
                    }
                };
                openApiMediaType.Encoding.Add("file", new OpenApiEncoding() { Style = ParameterStyle.Form });
                openApiMediaType.Schema.Properties.Add("file", new OpenApiSchema()
                {
                    Format = "binary",
                    Type = "string"
                });

                //必须传文件
                //openApiMediaType.Schema.Required.Add("file");

                operation.RequestBody.Content[fileUploadContentType] = openApiMediaType;

                foreach (var oldbodyContent in oldbodyContents)
                {
                    operation.RequestBody.Content[oldbodyContent.Key] = oldbodyContent.Value;
                }

            }


        }
    }
}
